package cn.backpackerxl.easyJDBC.util;

import cn.backpackerxl.easyJDBC.annotation.IgnoreField;

import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: backpackerxl
 * CreateTime: 2022/5/5
 * FileName: ReflectUtil
 **/
public final class ReflectUtil {
    private ReflectUtil() {
    }

    public static void doWithLocalSQLFields(Class<?> targetClass, FieldCompile fc) {
        for (Field field : targetClass.getDeclaredFields()) {
            try {
                field.setAccessible(true);
                fc.doWith(field);
            } catch (SQLException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public static void doWithLocalSQLFields(Class<?> targetClass, FieldCompiles fc) {
        Field[] fields = targetClass.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            try {
                fields[i].setAccessible(true);
                fc.doWith(fields[i], i + 1);
            } catch (SQLException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public static Map<String, Field> getMapFields(Class<?> clazz) {
        Map<String, Field> fieldMap = new HashMap<>();
        for (Field fi : clazz.getDeclaredFields()) {
            if (!fi.isAnnotationPresent(IgnoreField.class)) {
                fieldMap.put(StringUtil.removeHump(fi.getName()), fi);
            }
        }
        return fieldMap;
    }

    public static FieldObject getFields(Class<?> clazz) {
        return new FieldObject(clazz.getDeclaredFields());
    }
}
